package com.example.rg.generator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.rg.generator.DTO.DishDto;
import com.example.rg.generator.domain.Dish;
import com.example.rg.generator.domain.DishFlavor;
import com.example.rg.generator.service.DishFlavorService;
import com.example.rg.generator.service.DishService;
import com.example.rg.generator.mapper.DishMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DABB
 * @description 针对表【dish(菜品管理)】的数据库操作Service实现
 * @createDate 2023-04-28 09:43:31
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基本属性
        this.save(dishDto);
        //获取菜品id
        Long dishid = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map(M -> {
            //载入菜品id
            M.setDishId(dishid);
            return M;
        }).collect(Collectors.toList());
        // 保存菜品口味到口味表
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getWithFlavor(Long id) {
        //查询菜品基本信息
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        //载入
        BeanUtils.copyProperties(dish, dishDto);

        //查找当前菜品的(所有)口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavor = dishFlavorService.list(lqw);
        dishDto.setFlavors(dishFlavor);

        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新表的基本信息
        this.updateById(dishDto);
        //删除当前菜品的口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lqw);

        //添加当前的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map(M -> {
            M.setDishId(dishDto.getId());
            return M;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }
}




